package com.ucl.service.supplier.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ucl.dao.supplier.SupplierMapper;
import com.ucl.model.entity.supplier.Supplier;
import com.ucl.model.entity.supplier.SupplierTreeNode;
import com.ucl.model.entity.system.SysUserRole;
import com.ucl.service.supplier.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {

    @Autowired
    SupplierMapper supplierMapper;

    @Override
    public List<Supplier> listTreeSupplier() {
        return supplierMapper.selectList(new EntityWrapper<Supplier>().eq("is_delete", 0));
    }

    @Override
    public void saveSupplier(SupplierTreeNode supplier) {
        if (supplier.getId() != null) {
            removeSupplier(supplier);
        }
        /****** 在插入新的值 ******/
        //新增，则先保存父项，然后拿到父项id后保存子项
        supplier.setCreateTime(new Date());
        supplierMapper.insertSupplier(supplier); //自定义的方法，create_time，update_time等自动填充失效，可能是拦截问题
        for (SupplierTreeNode supplierTreeNode : supplier.getChildItemList()) {
            supplierTreeNode.setParentId(supplier.getId());
            supplierTreeNode.setCreateTime(new Date());
            supplierMapper.insert(supplierTreeNode);
        }
    }

    @Override
    public void deleteSupplier(Supplier supplier) {
        removeSupplier(supplier);
    }

    private void removeSupplier(Supplier supplier) {
        // 更新
        /******先将原来的父项和子项的is_delete=1 ******/

        Supplier oldSupplier = new Supplier();
        oldSupplier.setId(supplier.getId());
        oldSupplier.setDelete(Boolean.TRUE);
        supplierMapper.updateById(oldSupplier);
        // 获取原来的子项
        List<Supplier> childItemList = supplierMapper.selectList(new EntityWrapper<Supplier>().eq("parent_id", supplier.getId()));
        for (Supplier childItem : childItemList) {
            childItem.setDelete(Boolean.TRUE);
            supplierMapper.updateById(childItem);
        }
    }

}
